package com.rzjm.api.netty.water.business.inhandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.entity.DeviceWater;
import com.rzjm.api.netty.water.NettyUtil;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterService;
import com.rzjm.api.util.DateUtils;
import com.rzjm.api.util.OssUtil;
import com.rzjm.api.util.QRCodeUtilEx;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;

/**
 * 设备版本上报(初始化报文)
 * @author Mr.Zhou
 * @Description:
 * @date 2023/4/14 9:27
 */
@Component
public class Receive0InHandler implements InHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receive0InHandler.class);
    @Autowired
    private IDeviceWaterService devicesService;
    @Autowired
    private IDeviceWaterMessagesService deviceMessagesService;

    @Value("${web.uploadPath}")
    private String uploadPath;

    @Override
    public void handler(ChannelHandlerContext ctx, ReceiveData receiveData) {
        // 保存上报数据日志
        Optional.ofNullable(getMessage(receiveData))
            .ifPresent(message -> deviceMessagesService.save(message));
        LocalDateTime nowLd = LocalDateTime.now();
        Date nowDate = DateUtils.toDate(nowLd);
        String replyData;
        Integer deviceId;
        String imei = receiveData.getImei();
        if (StringUtils.isEmpty(imei)) {
            LOGGER.error("设备上报版本数据中imei为空！！");
            return;
        }
        boolean isExits = true;
        // 根据imei冲数据库查询设备，下发消息设置设备id，
        QueryWrapper<DeviceWater> qw = new QueryWrapper<>();
        qw.eq("imei", imei);
        qw.eq("device_sn", imei);
        qw.last("limit 1");
        DeviceWater devices = devicesService.getOne(qw);
        if (devices == null) {
            isExits = false;
            // 数据库没有设备，则新建设备，下发消息设置设备id，
            devices = new DeviceWater();
            devices.setDeviceSn(receiveData.getImei());
            devices.setOnlineState(1);
            devices.setLastOnlineTime(new Date());
            devices.setImei(receiveData.getCimi());
            devices.setImsi(receiveData.getImei());
            devices.setState(0);
            devices.setState(0);
            devices.setTankVolume(1500d);//是水箱体积 1.5吨
            devices.setTankLine(0d);//当前水位
            devices.setTankState(0);//水箱的状态 0 - 空了  1 - 中间  2 - 满了
            devices.setLightBoxState(0);//灯箱的状态  0 - 关闭 1 - 开启  2 - 报修
            devices.setOzoneState(0);//臭氧状态  0 - 关闭 1 - 开启  2 - 报修
            devices.setOzoneDuration(0);//臭氧开启时长   秒数
            devices.setOzoneInterval(0);//臭氧开启的周期   秒数
            devices.setSinglePayLimit(new BigDecimal(3));//单次消费限额
            devices.setSinglePrice(new BigDecimal(3));//单次打水的价格 （元）
            devices.setSingleDayLimit(new BigDecimal(100));//单日的消费限额
            devices.setSingleVolume(new BigDecimal(7.5));//单次打水的容量体积L
            devices.setVersion(receiveData.getVersion());//程序版本
            devices.setCreateTime(new Date());
            devices.setTemperature(0d);
            devices.setHumidity(0d);
        }
        devices.setImei(receiveData.getImei());
        devices.setImsi(receiveData.getCimi());
        devices.setVersion(receiveData.getVersion());

        if(isExits){
            devicesService.updateById(devices);
        }else{
            boolean bl = devicesService.save(devices);
            if(bl){
                String qrCode = "";

                String fileName = "deviceWater_qr_" + devices.getDeviceName() + ".jpg";
                String content = "https://www.sdyuedou.com/wxmini/water/info?sn=" + devices.getDeviceSn();

                int upload_type = OssUtil.TYPE_DEVICE_WATER_QR;
                System.out.println("content:  " + content);
                String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                try {
                    QRCodeUtilEx.createQrCodeImg(content, devices.getDeviceName(), null, uploadPath + "/" + img_key, true);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                qrCode = img_key;
                devices.setQrCode(qrCode);
                devicesService.updateById(devices);
            }
        }
        deviceId = devices.getId();

        //此时的设备ID无法从上报信息中获取，需要根据imei从数据库查询，如果数据库没有则创建一个设备，使用新设备的ID即可
        NettyUtil.addChannel(ctx, devices.getId());
        //回复消息
        replyData = "{\"rt\":0,\"id\":" + devices.getId() + ",\"v1\": "+ devices.getTankHeight() +"}";
        reply(replyData, deviceId);
    }
}
